﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace YYFIndexNow
{
    public static class IndexNowHelper
    {
        static HttpClient _client = new HttpClient();
        /// <summary>
        /// 提交IndexNow
        /// </summary>
        /// <param name="urls">提交的链接</param>
        /// <param name="host">域名</param>
        /// <param name="key">密钥：8-128位，UTF-8 编码的文本密钥文件{your-key}.txt，并防止网站根目录下</param>
        /// <param name="site">站点：如 https://www.iwmyx.cn/</param>
        /// <param name="indexnowurl">提交站点：Bing( https://www.bing.com/IndexNow)  IndexNow（https://api.indexnow.org/） Yandex（https://yandex.com/indexnow）</param>
        /// <returns>提交结果：成功或失败</returns>
        public static async Task<bool> SubmitAsync(List<string> urls, string host, string key, string site = "https://www.iwmyx.cn/", string indexnowurl = "https://www.bing.com/IndexNow")
        {
            if (urls == null || urls.Count == 0) { return false; }
            if (string.IsNullOrWhiteSpace(indexnowurl))
            {
                indexnowurl = "https://www.bing.com/IndexNow";
            }
            if (string.IsNullOrWhiteSpace(site))
            {
                site = $"https://www.{host}/";
            }
            var requestBody = new
            {
                host = host,
                key = key,
                keyLocation = $"{site}{key}.txt",
                urlList = urls
            };
            string jsonBody = System.Text.Json.JsonSerializer.Serialize(requestBody, new JsonSerializerOptions { IgnoreNullValues = true });
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            try
            {
                var response = await _client.PostAsync(indexnowurl, content);
                if (response.IsSuccessStatusCode)
                {
                    WriteHelper.WriteLog($"{urls.Count}条链接提交IndexNow成功");
                    return true;
                }
                else
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    WriteHelper.WriteLog($"{urls.Count}条链接提交IndexNow 失败：Status code: {response.StatusCode}  Response: {responseContent}");
                }
            }
            catch (Exception ex)
            {
                WriteHelper.WriteLog($"{urls.Count}条链接提交IndexNow 异常：{ex.Message}");
            }
            return false;
        }

        /// <summary>
        /// 提交IndexNow
        /// </summary>
        /// <param name="urls">提交的链接</param>
        /// <param name="host">域名</param>
        /// <param name="key">密钥：8-128位，UTF-8 编码的文本密钥文件{your-key}.txt，并防止网站根目录下</param>
        /// <param name="site">站点：如 https://www.iwmyx.cn/</param>
        /// <param name="indexnowurl">提交站点：Bing( https://www.bing.com/IndexNow)  IndexNow（https://api.indexnow.org/） Yandex（https://yandex.com/indexnow）</param>
        /// <returns>提交结果：成功或失败</returns>
        public static async Task SubmitBatchAsync(List<string> urls, string host, string key, string site = "https://www.iwmyx.cn/", string indexnowurl = "https://www.bing.com/IndexNow", int size = 1000)
        {
            int lookup = 0;
            for (int i = 0, j = urls.Count; i < j; i = size + i)
            {
                lookup++;
                var forlist = urls.Skip(i).Take(size).ToList();
                if (forlist.Count > 0)
                {
                    WriteHelper.WriteLog($"第{lookup}批[size:{size}]正在处理提交 Bing Indexnow ");
                    await SubmitAsync(forlist, host, key, site, indexnowurl);
                }
            }
        }
    }
}
